import Dexie from 'dexie'

class TodayExamineDatabase extends Dexie {
    constructor() {
        super('TodayExamineDatabase')
        this.version(1).stores({
            technicals: '++key,Tag,Info'
        })
        this.Technical = this.table('technicals')
    }
}

const db = new TodayExamineDatabase()

const AddItem = (Tag, Info) => {
    return new Promise((resolve, reject) => {
        db.transaction('rw', db.Technical, async () => {
            if ((await db.Technical.where({
                    Tag
                }).count()) === 0) {
                const id = await db.Technical.add({
                    Tag,
                    Info
                })
                resolve(id)
            } else {
                db.Technical.where({
                    Tag
                }).toArray().then(_ => {
                    resolve(_[0].key)
                    UpdateItem(_[0].key, {
                        Tag,
                        Info
                    })
                })
            }
        }).catch(e => {
            reject(e.stack || e)
        })
    })
}

const DeleteItem = (key) => {
    return new Promise((resolve, reject) => {
        db.transaction('rw', db.Technical, async () => {
            await db.Technical.delete(key).then(_ => {
                resolve(_)
            }).catch(e => {
                reject(e)
            })
        }).catch(e => {
            reject(e.stack || e)
        })
    })
}

const GetItem = (id) => {
    return new Promise((resolve, reject) => {
        db.transaction('rw', db.Technical, async () => {
            await db.Technical.filter(_ => {
                return _.key == id
            }).toArray().then(_ => {
                resolve(_)
            }).catch(e => {
                reject(e)
            })
        })
    })
}

const UpdateItem = (key, changes) => {
    return new Promise((resolve, reject) => {
        db.transaction('rw', db.Technical, async () => {
            await db.Technical.update(key, changes).then(_ => {
                resolve(_)
            }).catch(e => {
                reject(e)
            })
        })
    })
}

export {
    UpdateItem,
    GetItem,
    DeleteItem,
    AddItem
}